/*
 *接口编写处...
 *如果接口需要做Action的权限验证，请在Action上使用属性
 *如: [ApiActionPermission("GoodsBatchModel",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;

namespace VOL.demo.Controllers
{
    public partial class GoodsBatchModelController
    {
        private readonly IGoodsBatchModelService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public GoodsBatchModelController(
            IGoodsBatchModelService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 根据货品ID和仓库ID获取批次信息
        /// </summary>
        /// <param name="goodsId">货品ID</param>
        /// <param name="warehouseId">仓库ID</param>
        /// <returns></returns>
        [HttpGet("GetBatchesByGoodsAndWarehouse")]
        [AllowAnonymous]
        public IActionResult GetBatchesByGoodsAndWarehouse(long goodsId, long warehouseId)
        {
            try
            {
                var result = _service.GetBatchesByGoodsAndWarehouse(goodsId, warehouseId);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 批量保存批次信息
        /// </summary>
        /// <param name="batches">批次列表</param>
        /// <returns></returns>
        [HttpPost("SaveBatches")]
        [AllowAnonymous]
        public IActionResult SaveBatches([FromBody] List<GoodsBatchModel> batches)
        {
            try
            {
                var result = _service.SaveBatches(batches);
                if (result.Status)
                {
                    return Json(new { success = true, message = result.Message });
                }
                else
                {
                    return Json(new { success = false, message = result.Message });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 计算期初库存总量
        /// </summary>
        /// <param name="batches">批次列表</param>
        /// <returns></returns>
        [HttpPost("CalculateTotalQuantity")]
        [AllowAnonymous]
        public IActionResult CalculateTotalQuantity([FromBody] List<GoodsBatchModel> batches)
        {
            try
            {
                var total = _service.CalculateTotalQuantity(batches);
                return Json(new { success = true, data = total });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取货品批次与库存联查分页列表
        /// </summary>
        /// <param name="pageIndex">页码，默认1</param>
        /// <param name="pageSize">每页记录数，默认20</param>
        /// <param name="goodsId">货品ID（可选）</param>
        /// <param name="warehouseId">仓库ID（可选）</param>
        /// <param name="batchNo">批次号（可选）</param>
        /// <param name="keyword">搜索关键词（可选）</param>
        /// <returns></returns>
        [HttpGet("GetBatchInventoryPagedList")]
        [AllowAnonymous]
        public async Task<IActionResult> GetBatchInventoryPagedList(
            int pageIndex = 1,
            int pageSize = 20,
            long? goodsId = null,
            long? warehouseId = null,
            string batchNo = null,
            string keyword = null)
        {
            try
            {
                var result = await _service.GetBatchInventoryPagedListAsync(
                    pageIndex, 
                    pageSize, 
                    goodsId, 
                    warehouseId, 
                    batchNo, 
                    keyword);

                var response = new
                {
                    success = true,
                    data = result.Data,
                    totalCount = result.TotalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize),
                    hasPreviousPage = pageIndex > 1,
                    hasNextPage = pageIndex < Math.Ceiling((double)result.TotalCount / pageSize),
                    message = "获取货品批次库存联查列表成功"
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"获取货品批次库存联查列表失败：{ex.Message}" });
            }
        }
    }
}
